#include "gameLoopClient.h"
#include "comClient.h"

using namespace std;

// ----------
// inicializace
GameLoopClient::GameLoopClient(ComClient *aClient, std::string aClientIdent, CheckerColor player) {
	this->client = aClient;
	this->clientIdent = aClientIdent;
	this->Player = player;
}

// -----------
// spusti game loop
void GameLoopClient::Run() {
	if(this->ShakeHand() == false) {
		return;
	}

	// dokud server vyzaduje tahy
	while(this->ServerRequestMove()) {
		// vyber tah
		Move moveToSend = (*this->chooseMove)(this->currentBoard);
		
		// posli ho serveru
		if(this->SendMove(moveToSend) == false) {
			return;
		}
	}
}

// -----------
// Uvodni vymena inofrmaci na zacatku partie - identifikace kliena, barvy
bool GameLoopClient::ShakeHand() {
	// ----------
	// Send HELLO - identifikace klienta
	ComData helloMsg;
	helloMsg.Msg = HELLO;
	helloMsg.Player = this->Player;
	helloMsg.Identification = this->clientIdent;

	this->client->SendData(helloMsg);

	ComData helloMsgResp;
	this->client->RecieveData(&helloMsgResp);
	if(helloMsgResp.Msg != OK) {
		return false;
	}

	return true;
}

bool GameLoopClient::ServerRequestMove() {
	ComData serverMsg;
	this->client->RecieveData(&serverMsg);

	if(serverMsg.Msg == DO_MOVE) {
		this->currentBoard = serverMsg.CurrentBoard;
		return true;
	}

	return false;
}

// ----------
// odesle tah na server
bool GameLoopClient::SendMove(Move aMove) {
	ComData sendMoveMsg;
	sendMoveMsg.CurrentMove = aMove;
	sendMoveMsg.Msg = MOVE_SENT;
	client->SendData(sendMoveMsg);

	// zkontroluje odpoved
	ComData serverResponse;
	client->RecieveData(&serverResponse);
	if((serverResponse.Msg == MOVE_OK) || (serverResponse.Msg == MOVE_DID_NOT_CAPTURE)) {
		return true;
	}

	return false;
}